package com.tony.business.interceptor;

import cn.hutool.crypto.digest.DigestUtil;
import com.alibaba.fastjson.JSON;
import com.tony.domain.bo.JsonResult;
import com.tony.domain.exception.CustomException;
import com.tony.util.properties.SystemProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

/**
 * @author x
 */
@Component
@Slf4j
public class ApiInterceptor implements HandlerInterceptor {
    @Autowired
    SystemProperties systemProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if(systemProperties.getOnOff()) {
            log.info("apiInterceptor------------------------------------------------------");
            String token = request.getHeader("token");
            String timestamp = request.getHeader("timestamp");
            if (StringUtils.isEmpty(token) || StringUtils.isEmpty(timestamp)) {
                returnJson(response,new JsonResult<>(new CustomException("token或timestamp为空")));
                return false;
            }
            long now = Long.parseLong(timestamp);
            if (now + systemProperties.getMillisecond() < System.currentTimeMillis()) {
                returnJson(response,new JsonResult<>(new CustomException("timestamp超时")));
                return false;
            }
            String md5Hex = DigestUtil.md5Hex((timestamp + systemProperties.getSecurity() + timestamp).getBytes(StandardCharsets.UTF_8));
            if(md5Hex.equals(token)){
                return true;
            }else {
                returnJson(response,new JsonResult<>(new CustomException("token无效")));
                return false;
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) {

    }

    private void returnJson(HttpServletResponse response, JsonResult<Object> jsonResult) {
        String jsonString = JSON.toJSONString(jsonResult);
        log.info(jsonString);
        response.setCharacterEncoding("UTF-8");
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        try (PrintWriter writer = response.getWriter()) {
            writer.print(jsonString);
        } catch (IOException e) {
            log.info("拦截器输出流异常" + e);
        }
    }

}
